import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

import json,re,time,random,jieba,pickle,shutil,datetime
from keras.utils import pad_sequences
from keras.models import Sequential,Model,save_model,load_model


def predict_text_label(text):
    """
    预测一个文本的类别
    """
    # 加载信息
    num2label,tokenizer,maxlen,word2num = pickle.load(open('model/final_info.pkl','rb'))
    # 加载模型
    model = load_model('model/model.h5')

    # 分词
    texts = [text,]
    text_vector = tokenizer.texts_to_sequences(texts)
    sequences_pad = pad_sequences(
            text_vector,  # 二维列表 [[ num1,num2],,]
            maxlen = maxlen,  # 序列长度
            padding='post', #  长度低于maxlen时  pre 序列前补齐  post序列后补齐
            truncating='post', # 长度超出maxlen时 pre 序列前截断 post 序列后截断
            value=0.0, # 补齐的值
            dtype='int32',
        )
    label = model.predict(sequences_pad).argmax(axis=1)[0]
    print(label)
    labelch = num2label[label]
    print(f"预测的文本：{text}")
    print("---"*45)
    print(f"数字标签：{label} , 中文标签：{labelch}")
    print("\n")
    with open('./temp/output_file', 'w', encoding='utf-8') as f:
        f.write(labelch)

    pass

with open('./temp/input_file', 'r',encoding='utf-8') as f:
    lines = f.readlines()
    text = '\n'.join(lines)

predict_text_label(text)
